<template>
	<div class="my-goods-list">
		<MyTable :arr="list">
		<!-- 为了不写死子组件，将内容使用插槽的方式 -->
		<template #header >
				<th>#</th>
				<th>商品名称</th>
				<th>价格</th>
				<th>标签</th>
				<th>操作</th>
		</template>

		<template #body="scope">
		<td> {{ scope.obj.id }} </td>
				<td> {{ scope.obj.goods_name }} </td>
				<td> {{ scope.obj.goods_price }} </td>
				<td>
					<div>
						<!-- 输入框 -->
						<input style="width: 150px" 
						class="tag-input form-control" 
						type="text" 
						v-if="scope.obj.inputVisible"
						v-model.trim="scope.obj.inputValue"
						v-focus
						@blur="scope.obj.inputVisible = false"
						@keyup.esc="scope.obj.inputValue = ''"
						@keyup.enter="addFn(scope.obj)"
						/>
						<button class="btn btn-primary btn-sm add-tag" 
						v-else
						@click="scope.obj.inputVisible = true"
						>
							+Tags
						</button>
					</div>
						<span class="badge bg-warning text-dark"
						v-for="(item, index) in scope.obj.tags" :key="index"
						> 
									{{ item }} 
						</span>
				</td>
				<td><button class="btn btn-danger btn-sm" @click="del(scope.obj.id)">删除</button></td>
		</template>

		</MyTable>
	</div>
</template>

<script>
	// 接口：GTE  https://www.escook.cn/api/goods
import MyTable from '@/components/MyTable.vue'
import 'bootstrap/dist/css/bootstrap.css'
import axios from 'axios'

axios.defaults.baseURL = 'https://www.escook.cn'

	export default {
		components: {
			MyTable
		},
		data() {
			return {
				list: []
			};
		},
		created(){
			//在初始化钩子函数之后调用ajax请求
			this.getList()
		},
		methods:{
			//发送ajax请求
			async getList(){
				const {data: {data: res}} = await axios("/api/goods")
				console.log(res);
				//请求结果赋值给list
				this.list = res
			},
			del(id){
				this.list = this.list.filter(item => item.id !== id)
			},
			//添加标签功能
			addFn(obj){
				//判断为空不添加
				if(obj.inputValue === '') return 
				// 追加到标签数组
				obj.tags.push(obj.inputValue)
				//追加完成清空输入框
				obj.inputValue = ""
			}
		},
		directives: {
			focus:{
				inserted(el){
					el.focus()
				}
			}
		}
	};
</script>

<style>
</style>
